<script type="text/javascript" src="/homey.js" data-origin="settings"></script>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Xiaomi Mi Home</title>
<link type="text/css" rel="stylesheet" href="../assets/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="../assets/bootstrap-vue.min.css" />
<script src="../assets/vue.min.js"></script>
<script src="../assets/bootstrap-vue.min.js"></script>

<div id="miHome">
  <b-modal id="modalWelcomeScreen" hide-header-close no-close-on-backdrop hide-header scrollable>
    <template v-slot:default="{ hide }">
      <div class="text-center">
        <div class="pt-5 pb-3">
          <img
            style="width:100px"
            alt="logo"
            src=""
          />
        </div>
        <h1 class="font-weight-bold" style="font-size: 35px">Welcome to Xiaomi Mi Home App</h1>
        <b-container class="bv-example-row bv-example-row-flex-cols">
          <b-row class="pb-3">
            <b-col align-self="center" cols="3">
              <img
                class="float-right"
                style="width:32px;"
                alt="Xiaomi Mi Home"
                src=""
              />
            </b-col>
            <b-col align-self="center" class="text-left">
              <h1 style="padding-bottom: 0; margin: 0;">Xiaomi Gateway</h1>
              <small>You can add Xiaomi Gateway's and child devices.</small>
            </b-col>
          </b-row>
        </b-container>
      </div>
    </template>

    <template v-slot:modal-footer>
      <b-button block variant="success" style="color: #fff; background-color: #007bff; border-color: #007bff; padding: 10px;" @click="firstTimeLaunchConfirm">
        Continue
      </b-button>
    </template>
  </b-modal>

  <b-container fluid class="mt-3">
    <div v-if="loading" class="d-flex justify-content-center mt-5">
      <b-spinner style="width: 5rem; height: 5rem;" variant="primary" label="Large Spinner"></b-spinner>
    </div>
    <div v-if="mainPage">
      <div class="text-center">
        <b-list-group horizontal>
          <b-list-group-item :active="gatewaysPage" href="#" @click.prevent="showPageFromListGroup('gatewaysPage')">Gateways</b-list-group-item>
          <b-list-group-item :active="irDevicesPage" href="#" @click.prevent="showPageFromListGroup('irDevicesPage')">IR devices</b-list-group-item>
        </b-list-group>
      </div>
      <!-- Gateway page -->
      <div v-if="gatewaysPage">
        <div :class="setGatewaysPageMargin"></div>
        <div class="d-flex justify-content-center pt-2">
          <b-button style="color: #28a728; background-color: #fff; border: 1px solid transparent; border-color: #28a728; padding: .375rem .75rem;" @click.prevent="showHelpModal">Instructions</b-button>
        </div>
        <b-modal id="modalHowToStart" hide-header-close no-close-on-backdrop hide-header scrollable>
          <template v-slot:default
            ><div>
              <div class="text-center">
                <h4 style="color: rgb(255, 30, 30);">Note: Aqara gateways not supported.</h4>
              </div>
              <div class="d-flex justify-content-center m-2 pt-5"><h6>Add gateway using MAC and password:</h6></div>
              <div class="d-flex justify-content-center"><img src="https://raw.githubusercontent.com/jghaanstra/com.xiaomi-miio/master/docs/MAC_PASSWORD.gif" alt="placeholder 960" class="img-responsive" /></div>
              <div class="d-flex justify-content-center m-2 pt-5"><h6>Add gateway using IP and Token:</h6></div>
              <div class="d-flex justify-content-center pb-5">
                <img src="https://raw.githubusercontent.com/jghaanstra/com.xiaomi-miio/master/docs/IP_TOKEN_GENERATE.gif" alt="placeholder 960" class="img-responsive" />
              </div>
            </div>
          </template>

          <template v-slot:modal-footer="{ ok }">
            <b-button variant="success" @click="ok()">OK</b-button>
          </template>
        </b-modal>
        <div class="container pt-2 pb-2" v-for="(gateway, index) in gateways" :key="index">
          <div class="card">
            <div class="card-body ">
              <div class="message">
                <h4 class="card-text text-muted">GATEWAY</h4>
                <small>MAC: {{ gateway.mac }}</small><br>
                <small>PASSWORD: {{ gateway.password.toUpperCase() }}</small><br>
                <small>CONNECTED DEVICES: {{ getGateway(gateway.mac) }}</small>
              </div>
              <div class="actions float-right mt-3">
                <b-button variant="outline-success" style="color: #28a728; background-color: #fff; border: 1px solid transparent; border-color: #28a728; padding: .375rem .75rem;" @click.prevent="edit(gateway, index, 'gateway')">Modify</b-button>
                <b-button variant="outline-danger" style="color: #dc3545; background-color: #fff; border: 1px solid transparent; border-color: #dc3545; padding: .375rem .75rem;" @click.prevent="deleteDevice(gateway, index, 'gateway')">Delete</b-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- IR devices page -->
      <div v-if="irDevicesPage">
        <div :class="setIrDevicesPageMargin"></div>
        <div class="container pt-2 pb-2" v-for="(device, index) in irDevices" :key="index">
          <div class="card">
            <div class="card-body ">
              <div class="message">
                <h4 class="card-text text-muted">{{ device.ip }}</h4>
                <h6 class="card-text text-muted">{{ device.token }}</h6>
              </div>
              <div class="actions float-right mt-3">
                <b-button
                  variant="outline-success"
                  style="color: #28a728; background-color: #fff; border: 1px solid transparent; border-color: #28a728; padding: .375rem .75rem;"
                  @click.prevent="edit(device, index, 'irDevice')"
                  >Modify</b-button
                >
                <b-button
                  variant="outline-danger"
                  style="color: #dc3545; background-color: #fff; border: 1px solid transparent; border-color: #dc3545; padding: .375rem .75rem;"
                  @click.prevent="deleteDevice(device, index, 'irDevice')"
                  >Delete</b-button
                >
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- Add devices button -->
      <div>
        <b-button block variant="primary" style="color: #fff; background-color: #007bff; border-color: #007bff; padding: .375rem .75rem; position: fixed; bottom: 10px; width: 85%;" @click.prevent="addGatewayModalShow">Add</b-button>
      </div>
      <!-- Add devices modal -->
      <b-modal id="modalAddDevices" hide-header-close no-close-on-backdrop hide-header scrollable>
        <template v-slot:default>
          <div>
            <div class="text-center mt-5 mb-5" v-if="selectAddDeviceTypePage">
              <h1 class="pb-3">Select device type</h1>
              <b-list-group>
                <b-list-group-item button @click.prevent="chooseAddDeviceTypePage('gatewayMethod')" style="padding: .75rem 1.25rem; background-color: white; border: 1px solid rgba(0,0,0,.125); border-top-left-radius: .25rem; border-top-right-radius: .25rem; border-bottom-left-radius: 0px; border-bottom-right-radius: 0px; margin-bottom: -1px;">
                  Gateway
                </b-list-group-item>
                <b-list-group-item button @click.prevent="chooseAddDeviceTypePage('irDevice')" style="padding: .75rem 1.25rem; background-color: white; border: 1px solid rgba(0,0,0,.125); border-top-left-radius: .25rem; border-top-right-radius: .25rem; border-top-left-radius: 0px; border-top-right-radius: 0px; margin-bottom: -1px;">
                  IR device
                </b-list-group-item>
              </b-list-group>
            </div>
            <div class="text-center mt-5 mb-5" v-if="chooseGatewayAddMethodPage">
              <h1 class="pb-3">Choose add method</h1>
              <b-list-group>
                <b-list-group-item button @click.prevent="chooseAddDeviceTypePage('gateway')" style="padding: .75rem 1.25rem; background-color: white; border: 1px solid rgba(0,0,0,.125); border-top-left-radius: .25rem; border-top-right-radius: .25rem; border-top-right-radius: .25rem; border-bottom-left-radius: 0px; margin-bottom: -1px;">
                  MAC and Password
                </b-list-group-item>
                <b-list-group-item button @click.prevent="chooseAddDeviceTypePage('generatePassword')" style="padding: .75rem 1.25rem; background-color: white; border: 1px solid rgba(0,0,0,.125); border-top-left-radius: .25rem; border-top-right-radius: .25rem; border-top-left-radius: 0px; border-top-right-radius: 0px; margin-bottom: -1px;">
                  IP and Token (for generate password)
                </b-list-group-item>
              </b-list-group>
            </div>
            <div v-if="gatewayAddViaMacPage">
              <div role="group">
                <label class="font-weight-bold" for="input-live">MAC:</label>
                <b-form-input id="input-live" v-model="mac" :state="macRule" aria-describedby="input-live-help input-live-feedback" placeholder="Enter mac address" trim style="border: 1px solid #ced4da; padding: 10px;"></b-form-input>
                <b-form-invalid-feedback id="input-live-feedback">{{ macRuleMessage }}.</b-form-invalid-feedback>
                <b-form-text id="input-live-help">You can add a MAC address two points or without it. Upper and lower case is also not important.</b-form-text>
              </div>
              <div role="group" class="mt-3">
                <label class="font-weight-bold" for="input-live">Password:</label>
                <b-form-input id="input-live" v-model="password" :state="passwordRule" aria-describedby="input-live-help input-live-feedback" placeholder="Enter password" trim style="border: 1px solid #ced4da;  padding: 10px;"></b-form-input>
                <b-form-invalid-feedback id="input-live-feedback">Wrong password.</b-form-invalid-feedback>
                <b-form-text id="input-live-help">Upper and lower case is also not important.</b-form-text>
              </div>
              <div role="group">
                <label class="font-weight-bold" for="input-live">IP:</label>
                <b-form-input id="input-live" v-model="ip" :state="ipRule" aria-describedby="input-live-help input-live-feedback" placeholder="Enter IP address" trim style="border: 1px solid #ced4da; padding: 10px;"></b-form-input>
                <b-form-invalid-feedback id="input-live-feedback">{{ ipRuleMessage }}</b-form-invalid-feedback>
                <b-form-text id="input-live-help">Gateway IP address.</b-form-text>
              </div>
              <div role="group" class="mt-3">
                <label class="font-weight-bold" for="input-live">Token:</label>
                <b-form-input id="input-live" v-model="token" :state="tokenRule" aria-describedby="input-live-help input-live-feedback" placeholder="Enter token" trim style="border: 1px solid #ced4da; padding: 10px;"></b-form-input>
                <b-form-invalid-feedback id="input-live-feedback">{{ tokenRuleMessage }}</b-form-invalid-feedback>
                <b-form-text id="input-live-help">Gateway token.</b-form-text>
              </div>
            </div>
            <!-- Generate MAC and Password from IP and Token -->
            <div v-if="gatewayAddViaGeneratePage">
              <div v-if="generatePasswordLoading">
                <div class="d-flex justify-content-center mt-5">
                  <b-spinner style="width: 5rem; height: 5rem;" variant="primary" label="Large Spinner"></b-spinner>
                </div>
                <div class="text-center m-5">
                  <h1 v-if="gatewayAddViaGeneratePage">Generating...</h1>
                </div>
              </div>
              <div v-if="!generatePasswordLoading">
                <div role="group">
                  <label class="font-weight-bold" for="input-live">IP:</label>
                  <b-form-input id="input-live" v-model="ip" :state="ipRule" aria-describedby="input-live-help input-live-feedback" placeholder="Enter IP address" trim style="border: 1px solid #ced4da; padding: 10px;"></b-form-input>
                  <b-form-invalid-feedback id="input-live-feedback">{{ ipRuleMessage }}</b-form-invalid-feedback>
                  <b-form-text id="input-live-help">Gateway IP address.</b-form-text>
                </div>
                <div role="group" class="mt-3">
                  <label class="font-weight-bold" for="input-live">Token:</label>
                  <b-form-input id="input-live" v-model="token" :state="tokenRule" aria-describedby="input-live-help input-live-feedback" placeholder="Enter token" trim style="border: 1px solid #ced4da; padding: 10px;"></b-form-input>
                  <b-form-invalid-feedback id="input-live-feedback">{{ tokenRuleMessage }}</b-form-invalid-feedback>
                  <b-form-text id="input-live-help">Gateway token.</b-form-text>
                </div>
                <div class="m-3 text-center" v-if="generatingResult" style="color: #28a745;">{{ generatingResultMessage }}</div>
                <div class="m-3 text-center" v-if="generatingResult" style="color: #28a745;">MAC is: {{ mac }}</div>
                <div class="m-3 text-center" v-if="generatingResult" style="color: #28a745;">Generated password is: {{ password }}</div>
                <div class="mt-3">
                  <b-button block variant="success" style="color: #fff; background-color: #28a745; border-color: #28a745; padding: 10px;" @click="generatePassword" :disabled="generatePasswordLoading">
                    Generate and Add
                  </b-button>
                </div>
              </div>
            </div>
            <div v-if="irDeviceAddPage">
              <div v-if="checkConnectionLoading">
                <div class="d-flex justify-content-center mt-5">
                  <b-spinner style="width: 5rem; height: 5rem;" variant="primary" label="Large Spinner"></b-spinner>
                </div>
                <div class="text-center m-5">
                  <h1 v-if="irDeviceAddPage">Connecting...</h1>
                </div>
              </div>
              <div v-if="!checkConnectionLoading">
                <div role="group">
                  <label class="font-weight-bold" for="input-live">IP:</label>
                  <b-form-input id="input-live" v-model="ip" :state="ipRule" aria-describedby="input-live-help input-live-feedback" placeholder="Enter IP address" trim style="border: 1px solid #ced4da; padding: 10px;"></b-form-input>
                  <b-form-invalid-feedback id="input-live-feedback">{{ ipRuleMessage }}</b-form-invalid-feedback>
                  <b-form-text id="input-live-help">Device IP address.</b-form-text>
                </div>
                <div role="group" class="mt-3">
                  <label class="font-weight-bold" for="input-live">Token:</label>
                  <b-form-input id="input-live" v-model="token" :state="tokenRule" aria-describedby="input-live-help input-live-feedback" placeholder="Enter token" trim style="border: 1px solid #ced4da; padding: 10px;"></b-form-input>
                  <b-form-invalid-feedback id="input-live-feedback">{{ tokenRuleMessage }}</b-form-invalid-feedback>
                  <b-form-text id="input-live-help">Device token.</b-form-text>
                </div>
                <div class="m-3 text-center" v-if="connectionTest" style="color: #28a745;">{{ connectionTestMessage }}</div>
                <div class="mt-3">
                  <b-button block variant="outline-success" style="color: #28a728; background-color: #fff; border: 1px solid transparent; border-color: #28a728; padding: 10px;" @click="checkConnection" :disabled="checkConnectionLoading">
                    Check to connect
                  </b-button>
                </div>
              </div>
            </div>
          </div>
        </template>

        <template v-slot:modal-footer>
          <b-button variant="success" style="color: #fff; background-color: #6c757d; border-color: #6c757d; padding: .375rem .75rem;" @click="modalAddDevicesClose">
            Cancel
          </b-button>
          <b-button v-if="addDeviceButton" variant="success" style="color: #fff; background-color: #007bff; border-color: #007bff; padding: .375rem .75rem;" @click="addDevice">
            Add {{ addDeviceType }}
          </b-button>
        </template>
      </b-modal>
      <!-- edit devices modal -->
      <b-modal id="modalEditDevices" hide-header-close no-close-on-backdrop hide-header scrollable>
        <template v-slot:default>
          <div>
            <div v-if="gatewayEditPage">
              <div role="group">
                <label class="font-weight-bold" for="input-live">MAC:</label>
                <b-form-input id="input-live" v-model="mac" :state="macEditRule" aria-describedby="input-live-help input-live-feedback" placeholder="Enter mac address" trim style="border: 1px solid #ced4da; padding: 10px;"></b-form-input>
                <b-form-invalid-feedback id="input-live-feedback"> {{ macRuleMessage }} </b-form-invalid-feedback>
                <b-form-text id="input-live-help">You can add a MAC address two points or without it. Upper and lower case is also not important.</b-form-text>
              </div>
              <div role="group" class="mt-3">
                <label class="font-weight-bold" for="input-live">Password:</label>
                <b-form-input id="input-live" v-model="password" :state="passwordEditRule" aria-describedby="input-live-help input-live-feedback" placeholder="Enter password" trim style="border: 1px solid #ced4da; padding: 10px;"></b-form-input>
                <b-form-invalid-feedback id="input-live-feedback"> {{ passwordRuleMessage }} </b-form-invalid-feedback>
                <b-form-text id="input-live-help">Upper and lower case is also not important.</b-form-text>
              </div>
              <div role="group">
                <label class="font-weight-bold" for="input-live">IP:</label>
                <b-form-input id="input-live" v-model="ip" :state="ipEditRule" aria-describedby="input-live-help input-live-feedback" placeholder="Enter IP address" trim style="border: 1px solid #ced4da; padding: 10px;"></b-form-input>
                <b-form-invalid-feedback id="input-live-feedback">{{ ipRuleMessage }}</b-form-invalid-feedback>
                <b-form-text id="input-live-help">Gateway IP address.</b-form-text>
              </div>
              <div role="group" class="mt-3">
                <label class="font-weight-bold" for="input-live">Token:</label>
                <b-form-input id="input-live" v-model="token" :state="tokenEditRule" aria-describedby="input-live-help input-live-feedback" placeholder="Enter token" trim style="border: 1px solid #ced4da; padding: 10px;"></b-form-input>
                <b-form-invalid-feedback id="input-live-feedback">{{ tokenRuleMessage }}</b-form-invalid-feedback>
                <b-form-text id="input-live-help">Gateway token.</b-form-text>
              </div>
            </div>
            <div v-if="irDeviceEditPage">
              <div v-if="checkConnectionLoading">
                <div class="d-flex justify-content-center mt-5">
                  <b-spinner style="width: 5rem; height: 5rem;" variant="primary" label="Large Spinner"></b-spinner>
                </div>
                <div class="text-center m-5">
                  <h1 v-if="irDeviceAddPage">Connecting...</h1>
                </div>
              </div>
              <div v-if="!checkConnectionLoading">
                <div role="group">
                  <label class="font-weight-bold" for="input-live">IP:</label>
                  <b-form-input id="input-live" v-model="ip" :state="ipEditRule" aria-describedby="input-live-help input-live-feedback" placeholder="Enter IP address" trim style="border: 1px solid #ced4da; padding: 10px;"></b-form-input>
                  <b-form-invalid-feedback id="input-live-feedback">{{ ipRuleMessage }}</b-form-invalid-feedback>
                  <b-form-text id="input-live-help">Device IP address.</b-form-text>
                </div>
                <div role="group" class="mt-3">
                  <label class="font-weight-bold" for="input-live">Token:</label>
                  <b-form-input id="input-live" v-model="token" :state="tokenEditRule" aria-describedby="input-live-help input-live-feedback" placeholder="Enter token" trim style="border: 1px solid #ced4da; padding: 10px;"></b-form-input>
                  <b-form-invalid-feedback id="input-live-feedback">{{ tokenRuleMessage }}</b-form-invalid-feedback>
                  <b-form-text id="input-live-help">Device token.</b-form-text>
                </div>
                <div class="mt-3">
                  <b-button block variant="outline-success" style="color: #28a728; background-color: #fff; border: 1px solid transparent; border-color: #28a728; padding: .375rem .75rem;" @click="checkConnection" :disabled="checkConnectionLoading">
                    Connect to check
                  </b-button>
                </div>
              </div>
            </div>
          </div>
        </template>

        <template v-slot:modal-footer>
          <b-button variant="success" style="color: #fff; background-color: #6c757d; border-color: #6c757d; padding: .375rem .75rem;" @click="modalAddDevicesClose">Cancel</b-button>
          <b-button variant="success" style="color: #fff; background-color: #007bff; border-color: #007bff; padding: .375rem .75rem;" @click="save">Save</b-button>
        </template>
      </b-modal>
    </div>
  </b-container>
</div>

<script type="text/javascript">
  function onHomeyReady(Homey) {
    Homey.ready();
    new Vue({
      el: "#miHome",
      data() {
        return {
          gateways: [],
          irDevices: [],
          gatewaysObject: {},
          currentPage: "gateways",
          loading: true,
          mainPage: false,
          gatewaysPage: true,
          irDevicesPage: false,
          addDeviceType: null,
          selectAddDeviceTypePage: true,
          chooseGatewayAddMethodPage: false,
          gatewayAddViaMacPage: false,
          gatewayAddViaGeneratePage: false,
          irDeviceAddPage: false,
          mac: "",
          macRule: null,
          macRuleMessage: "",
          password: "",
          passwordRule: null,
          passwordRuleMessage: "",
          ip: "",
          ipRule: null,
          ipRuleMessage: "",
          token: "",
          tokenRule: null,
          tokenRuleMessage: "",
          addDeviceButton: false,
          generatePasswordLoading: false,
          generatingResult: false,
          generatingResultMessage: "",
          checkConnectionLoading: false,
          gatewayEditPage: false,
          irDeviceEditPage: false,
          editIndex: 0,
          saveDeviceType: "",
          connectionTest: false,
          connectionTestMessage: ""
        };
      },
      mounted() {
        this.checkFirstTimeLaunch();
        this.getDevices();
        this.getGatewayDeviceAction();
      },
      methods: {
        checkFirstTimeLaunch() {
          Homey.get("firstTimeLaunch", (error, firstTimeLaunch) => {
            if (error) return Homey.alert(error);
            if (firstTimeLaunch == null) {
              this.$bvModal.show("modalWelcomeScreen");
            } else {
              this.loading = false;
              this.mainPage = true;
            }
          });
        },
        firstTimeLaunchConfirm() {
          this.$bvModal.hide("modalWelcomeScreen");
          this.loading = false;
          this.mainPage = true;
          Homey.set("firstTimeLaunch", "launched", error => {
            if (error) return Homey.alert(error);
            this.$bvModal.hide("modalWelcomeScreen");
            this.loading = false;
            this.mainPage = true;
          });
        },
        getDevices() {
          Homey.get("gatewaysList", (error, list) => {
            if (error) return Homey.alert(error);

            this.gateways = list || [];
          });

          Homey.get("irDevicesList", (error, list) => {
            if (error) return Homey.alert(error);

            this.irDevices = list || [];
          });
        },
        showPageFromListGroup(page) {
          if (page == "gatewaysPage") {
            this.gatewaysPage = true;
            this.irDevicesPage = false;
          } else if (page == "irDevicesPage") {
            this.irDevicesPage = true;
            this.gatewaysPage = false;
          }
        },
        addGatewayModalShow() {
          this.$bvModal.show("modalAddDevices");
        },
        addDevice(update = "add") {
          if (this.mac.length == 12) {
            if (this.mac.match(/\b[0-9A-Fa-f]{12}\b/g)) {
              this.macRule = true;
            } else {
              this.macRule = false;
              this.macRuleMessage = "Wrong MAC address";
            }
          } else if (this.mac.length == 17) {
            if (this.mac.match(/^[0-9a-f]{1,2}([:])[0-9a-f]{1,2}(?:\1[0-9a-f]{1,2}){4}$/i)) {
              this.macRule = true;
            } else {
              this.macRule = false;
              this.macRuleMessage = "Wrong MAC address";
            }
          } else {
            this.macRule = false;
            this.macRuleMessage = "Wrong MAC address";
          }

          if (this.password.length == 16) {
            if (this.password.match(/\b[0-9A-Fa-f]{16}\b/g)) {
              this.passwordRule = true;
            } else {
              this.passwordRule = false;
              this.passwordRuleMessage = "Wrong password";
            }
          } else {
            this.passwordRule = false;
            this.passwordRuleMessage = "Wrong password";
          }

          if (this.ip.match(/^(?:(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)\.){3}(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)(?:\:(?:\d|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5]))?$/)) {
            this.ipRule = true;
          } else {
            this.ipRule = false;
            this.ipRuleMessage = "Wrong IP address.";
          }

          if (this.token.length == 32) {
            if (this.token.match(/\b[0-9A-Fa-f]{32}\b/g)) {
              this.tokenRule = true;
            } else {
              this.tokenRule = false;
              this.tokenRuleMessage = "Wrong token.";
            }
          } else {
            this.tokenRule = false;
            this.tokenRuleMessage = "Wrong token.";
          }

          if (this.macRule && this.passwordRule && update != "generate") {
            if (this.gateways.filter(gateway => gateway.mac == this.mac).length != 0) {
              this.macRule = false;
              this.macRuleMessage = "This mac address already exists";
            } else {
              this.gateways.push({ mac: this.mac.split(":").join(""), password: this.password });

              Homey.set("gatewaysList", this.gateways, (error, settings) => {
                if (error) return Homey.alert(error);
              });
              this.modalAddDevicesClose();
              this.showPageFromListGroup("gatewaysPage");
            }
          } else if (this.ipRule && this.tokenRule && update != "generate") {
            if (this.irDevices.filter(device => device.ip == this.ip).length != 0) {
              let irDevicesMacs = this.irDevices.map(device => device.ip);
              let indexDevice = irDevicesMacs.indexOf(this.ip);
              this.irDevices[indexDevice].token = this.token;

              Homey.set("irDevicesList", this.irDevices, (error, settings) => {
                if (error) return Homey.alert(error);
              });
              this.showPageFromListGroup("irDevicesPage");

              this.modalAddDevicesClose();
            } else {
              this.irDevices.push({ ip: this.ip, token: this.token });

              Homey.set("irDevicesList", this.irDevices, (error, settings) => {
                if (error) return Homey.alert(error);
              });
              this.showPageFromListGroup("irDevicesPage");

              this.modalAddDevicesClose();
            }
          } else if (update == "generate") {
            if (this.gateways.length == 0) {
              this.addDevice();
            } else {
              this.mac = this.mac.toLowerCase();
              let gatewayMacs = this.gateways.map(gateway => gateway.mac);
              let indexDevice = gatewayMacs.indexOf(this.mac);
              if (indexDevice < 0) {
                this.addDevice();
              } else {
                this.gateways[indexDevice].password = this.password;
                this.gateways.sort();
                Homey.set("gatewaysList", this.gateways, (error, settings) => {
                  if (error) return Homey.alert(error);
                });
                this.modalAddDevicesClose();
                this.showPageFromListGroup("gatewaysPage");
              }
            }
          }
        },
        chooseAddDeviceTypePage(page) {
          this.selectAddDeviceTypePage = false;
          if (page == "gateway") {
            this.addDeviceType = "gateway";
            this.addDeviceButton = true;
            this.gatewayAddViaMacPage = true;
            this.gatewayAddViaGeneratePage = false;
            this.irDeviceAddPage = false;
            this.chooseGatewayAddMethodPage = false;
          } else if (page == "gatewayMethod") {
            this.chooseGatewayAddMethodPage = true;
            this.gatewayAddViaGeneratePage = false;
            this.gatewayAddViaMacPage = false;
            this.irDeviceAddPage = false;
          } else if (page == "generatePassword") {
            this.addDeviceType = "gateway";
            this.gatewayAddViaGeneratePage = true;
            this.chooseGatewayAddMethodPage = false;
            this.gatewayAddViaMacPage = false;
            this.irDeviceAddPage = false;
          } else if (page == "irDevice") {
            this.addDeviceType = "ir device";
            this.irDeviceAddPage = true;
            this.addDeviceButton = true;
            this.gatewayAddViaGeneratePage = false;
            this.gatewayAddViaMacPage = false;
          }
        },
        modalAddDevicesClose() {
          this.$bvModal.hide("modalAddDevices");
          this.$bvModal.hide("modalEditDevices");

          setTimeout(() => {
            this.selectAddDeviceTypePage = true;
            this.chooseGatewayAddMethodPage = false;
            this.gatewayAddViaMacPage = false;
            this.irDeviceAddPage = false;
            this.gatewayAddViaGeneratePage = false;
            this.addDeviceType = null;
            this.addDeviceButton = false;
            this.mac = "";
            this.macRule = null;
            this.macRuleMessage = "Wrong MAC address";
            this.ip = "";
            this.ipRule = null;
            this.ipRuleMessage = "Wrong IP address";
            this.password = "";
            this.passwordRule = null;
            this.passwordRuleMessage = "Wrong password";
            this.token = "";
            this.tokenRule = null;
            this.tokenRuleMessage = "Wrong token";
            this.connectionTest = false;
            this.connectionTestMessage = "";
            this.checkConnectionLoading = false;
            this.generatingResult = false;
            this.generatingResultMessage = "";
            this.generatePasswordLoading = false;
          }, 150);
        },
        generatePassword() {
          this.generatePasswordLoading = true;
          this.ipRule = null;
          this.ipRuleMessage = "";
          this.tokenRule = null;
          this.tokenRuleMessage = "";

          Homey.api('POST', '/generate', { ip: this.ip, token: this.token })
            .then(result => {
              if (result.status == "OK") {
                this.generatingResult = true;
                this.generatePasswordLoading = false;
                this.generatingResultMessage = "Successfully generated";
                this.mac = result.mac;
                this.password = result.password;

                setTimeout(() => {
                  this.checkConnectionLoading = false;
                  this.generatingResult = false;
                  this.generatingResultMessage = "";
                  this.addDevice("generate");
                  setTimeout(() => {
                    this.getGatewayDeviceAction();
                  }, 1000);
                }, 1500);
              }
            })
            .catch(error => {
              this.generatingResult = true;
              this.generatePasswordLoading = false;
              this.generatingResultMessage = error.message;

              if (error.message == "Could not connect to device, handshake timeout") {
                this.ipRule = false;
                this.ipRuleMessage = "Wrong IP address or device offline";
              } else if (error.message == "Could not connect to device, token might be wrong") {
                this.tokenRule = false;
                this.tokenRuleMessage = "Wrong token";
              }
            });
        },
        checkConnection() {
          this.checkConnectionLoading = true;
          Homey.api('POST', '/testConnection', { ip: this.ip, token: this.token })
            .then(result => {
              if (result.token == this.token) {
                this.checkConnectionLoading = false;
                this.generatePasswordLoading = false;
                this.connectionTest = true;
                this.connectionTestMessage = "Successfully connected";
              }
            })
            .catch(error => {
              this.connectionTest = true;
              this.checkConnectionLoading = false;
              this.connectionTestMessage = error.message;

              if (error.message == "Could not connect to device, handshake timeout") {
                this.ipRule = false;
                this.ipRuleMessage = "Wrong IP address or device offline";
              } else if (error.message == "Could not connect to device, token might be wrong") {
                this.tokenRule = false;
                this.tokenRuleMessage = "Wrong token";
              }
            });
        },
        edit(device, index, type) {
          if (type == "gateway") {
            this.gatewayEditPage = true;
            this.irDeviceEditPage = false;
            this.mac = device.mac;
            this.password = device.password;
            this.ip = device.ip || "0.0.0.0";
            this.token = device.token || "00000000000000000000000000000000";
          } else if (type == "irDevice") {
            this.irDeviceEditPage = true;
            this.gatewayEditPage = false;
            this.ip = device.ip;
            this.token = device.token;
          }
          this.editIndex = index;
          this.saveDeviceType = type;
          this.$bvModal.show("modalEditDevices");
        },
        deleteDevice(device, index, type) {
          if (type == "gateway") {
            this.gateways.splice(index, 1);
            Homey.set("gatewaysList", this.gateways, (error, settings) => {
              if (error) return Homey.alert(error);
            });
          } else if (type == "irDevice") {
            this.irDevices.splice(index, 1);
            Homey.set("irDevicesList", this.irDevices, (error, settings) => {
              if (error) return Homey.alert(error);
            });
          }
        },
        save() {
          if (this.saveDeviceType == "gateway") {
            this.gateways[this.editIndex] = { mac: this.mac.split(":").join(""), password: this.password, ip: this.ip, token: this.token };
            this.gateways.sort();
            Homey.set("gatewaysList", this.gateways, (error, settings) => {
              if (error) return Homey.alert(error);
            });
            this.modalAddDevicesClose();
          } else if (this.saveDeviceType == "irDevice") {
            this.irDevices[this.editIndex] = { ip: this.ip, token: this.token };
            this.irDevices.sort();
            Homey.set("irDevicesList", this.irDevices, (error, settings) => {
              if (error) return Homey.alert(error);
            });
            this.modalAddDevicesClose();
          }
        },
        showHelpModal() {
          this.$bvModal.show("modalHowToStart");
        },
        getGatewayDeviceAction() {
          Homey.api('GET', '/getGateways', {})
            .then(result => { this.gatewaysObject = result; })
            .catch(error => { return error; });
        },
        getGateway(sid) {
          if (this.gatewaysObject[sid] && this.gatewaysObject[sid].childDevices) {
            return this.gatewaysObject[sid].childDevices.length;
          } else {
            return null;
          }
        }
      },
      computed: {
        macEditRule() {
          if (this.mac.length == 12) {
            if (this.mac.match(/\b[0-9A-Fa-f]{12}\b/g)) {
              return true;
            } else {
              this.macRuleMessage = "Wrong MAC address";
              return false;
            }
          } else if (this.mac.length == 17) {
            if (this.mac.match(/^[0-9a-f]{1,2}([:])[0-9a-f]{1,2}(?:\1[0-9a-f]{1,2}){4}$/i)) {
              return true;
            } else {
              this.macRuleMessage = "Wrong MAC address";
              return false;
            }
          } else if (this.mac.length == 0) {
            this.macRuleMessage = "This field should not be empty";
            return false;
          } else {
            this.macRuleMessage = "Wrong MAC address";
            return false;
          }
        },
        passwordEditRule() {
          if (this.password.length == 16) {
            if (this.password.match(/\b[0-9A-Fa-f]{16}\b/g)) {
              return true;
            } else {
              this.passwordRuleMessage = "Wrong password";
              return false;
            }
          } else if (this.password.length == 0) {
            this.passwordRuleMessage = "This field should not be empty";
            return false;
          } else {
            this.passwordRuleMessage = "Wrong password";
            return false;
          }
        },
        ipEditRule() {
          if (this.ip.match(/^(?:(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)\.){3}(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)(?:\:(?:\d|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5]))?$/)) {
            return true;
          } else if (this.ip.length == 0) {
            this.ipRuleMessage = "This field should not be empty";
            return false;
          } else {
            this.ipRuleMessage = "Wrong IP address";
            return false;
          }
        },
        tokenEditRule() {
          if (this.token.length == 32) {
            if (this.token.match(/\b[0-9A-Fa-f]{32}\b/g)) {
              return true;
            } else {
              this.tokenRuleMessage = "Wrong token";
              return false;
            }
          } else if (this.token.length == 0) {
            this.tokenRuleMessage = "This field should not be empty";
            return false;
          } else {
            this.tokenRuleMessage = "Wrong token";
            return false;
          }
        },
        setGatewaysPageMargin() {
          return this.gateways.length == 0 ? "m-5" : null;
        },
        setIrDevicesPageMargin() {
          return this.irDevices.length == 0 ? "m-5" : null;
        }
      }
    });
  }
</script>